import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'dart:typed_data';
import 'lib_bt.dart';

import 'listener/BleEvent.dart';

//蓝牙工具类
class BleManager extends ChangeNotifier with BleEvent {
  static BleManager? _instance;

  static BleManager get instance => _instance ??= BleManager._();
  late LibBt _libBtPlugin;

  BleManager._() {
    _libBtPlugin = LibBt();
    //设置连接回调监听
    _libBtPlugin.setOnBleConnectListener(this);
    _libBtPlugin.setOnBleScanListener(this);
    _libBtPlugin.setOnOtaListener(this);
    _libBtPlugin.setOnBleDataListener(this);
  }

  ///设置UUID配置信息
  void setUUIDInfo(String json) {
    _libBtPlugin.setUUIDInfo(json);
  }

  ///打开gps
  void openGps() {
    _libBtPlugin.openGps();
  }

  ///打开蓝牙
  void openBle() {
    _libBtPlugin.openBle();
  }

  ///蓝牙是否已经开启
  Future<bool> isBleEnable() async {
    var enable = await _libBtPlugin.isBleEnable();
    return enable ?? false;
  }

  /// GPS是否打开
  Future<bool> isGpsEnable() async {
    var enable = await _libBtPlugin.isGpsEnable();
    return enable ?? false;
  }

  ///开始扫描
  /// scanTime 扫描时间，单位毫秒
  void startScan({int scanTime = 15 * 1000}) async {
    if (isScanning()) {
      return;
    }

    ///清空未连接的蓝牙
    clearUnConnect();
    _libBtPlugin.startScan(scanTime);
  }

  ///断开连接指定蓝牙设备
  void disconnect(String address) {
    _libBtPlugin.disconnect(address);
  }

  ///连接指定蓝牙设备
  void connect(String address) {
    isConnecting = true;
    var checkBleSupportInterfaceForAddress = getCheckBleSupportInterfaceForAddress(address);
    if (checkBleSupportInterfaceForAddress != null) {
      setUUIDInfo(checkBleSupportInterfaceForAddress.getUUIDInfo());
    }
    _libBtPlugin.connect(address);
  }

  ///停止扫描
  void stopScan() async {
    _libBtPlugin.stopScan();
  }

  @override
  void notifyListener() {
    notifyListeners();
  }

  ///开始ota升级
  void startOta(String address, Uint8List data) {
    _libBtPlugin.startOta(address, data);
  }

  ///是否是正在升级
  Future<bool> isOTA() async {
    return _libBtPlugin.isOTA();
  }

  ///写出数据
  void write(String address, String serviceUuid, String uuid, List<int> data) {
    print("write: $address $serviceUuid $uuid ${jsonEncode(data)}");
    _libBtPlugin.write(address, serviceUuid, uuid, data);
  }
}
